<?php

namespace app\admin\controller;

use app\BaseController;
use app\service\admin\AdminPurviewLogic;
use app\service\admin\AdminRoleLogic;

class Role extends BaseController
{
    public function index()
    {
        $arrTemplate = [
            ['field' => 'id', 'title' => 'id'],
            ['field' => 'name', 'title' => '角色'],
            ['field' => 'desc', 'title' => '描述'],
            ['field' => 'create_dt', 'title' => '创建时间'],
            ['field' => '', 'title' => '操作', 'toolbar' => '#rowBar'],
        ];
        $template = json_encode($arrTemplate);
        $name = $this->request->param('name');
        $limit = $this->request->param('limit');
        if (!$this->request->isPost()) {
            return view('', compact('template', 'name', 'limit'));
        } else {
            $arrData = AdminRoleLogic::getInstance()->getList($name, $limit);
            return success('', $arrData);
        }
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $arrParam = $this->request->all();

            try {
                AdminRoleLogic::getInstance()->add($arrParam['name'], $arrParam['desc']);
            } catch (\Exception $e) {
                return error($e->getMessage());
            }
            return success('已添加');
        } else {
            return view('');
        }
    }

    public function edit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $arrParam = $this->request->all();
            try {
                AdminRoleLogic::getInstance()->edit($id, $arrParam['name'], $arrParam['desc']);
            } catch (\Exception $e) {
                return error($e->getMessage());
            }
            return success('已更新');
        } else {
            $arrData = AdminRoleLogic::getInstance()->getRowById($id);
            return view('', ['arrData' => $arrData]);
        }
    }

    public function del()
    {
        $id = $this->request->param('id');
        AdminRoleLogic::getInstance()->del($id);
        return success('已删除');
    }

    public function privilege()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $purviewIds = request()->post("purview_ids");
            AdminPurviewLogic::getInstance()->privilege($id, $purviewIds);
            return success('已分配');
        } else {
            $arrData = AdminRoleLogic::getInstance()->getRowById($id);
            if ($arrData['super'] == AdminRoleLogic::SUPER) {
                return error('超级管理员不用分配权限');
            }
            $arrList = AdminPurviewLogic::getInstance()->getAll($id);
            return view('', compact('arrList'));
        }
    }
}